package com.unitspirit.sample.cmbchina;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import  com.auth0.jwt.interfaces.DecodedJWT;
import org.apache.commons.lang3.time.DateUtils;

import java.util.Date;

public class JwtSample {

    public void creatToken(){
        try{
            Algorithm algorithm = Algorithm.HMAC256("secret");
            String token = JWT.create()
                    .withIssuer("auth0")    // 发布者
                    .withIssuedAt(new Date())   // 生成签名的时间
                    .withExpiresAt(DateUtils.addHours(new Date(),2))   // 生成签名的有效期,小时
                    .withClaim("name","wuyuwei") // 插入数据
                    .sign(algorithm);

            System.out.println(token);
        }catch(JWTCreationException e){
            e.printStackTrace();
            //如果Claim不能转换为JSON，或者在签名过程中使用的密钥无效，那么将会抛出JWTCreationException异常。
        }


    }
    public void verifierToken(){
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsIm5hbWUiOiJ3dXl1d2VpIiwiZXhwIjoxNTc4NzM4ODc4LCJpYXQiOjE1Nzg3MzE2Nzh9.B1TBjznMRsnIVsKEQDrkpLIA5AwLhoot3wE3e1KeM3Y";
        try {
            Algorithm algorithm = Algorithm.HMAC256("secret");
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("auth0") //匹配指定的token发布者 auth0
                    .build();
            DecodedJWT jwt = verifier.verify(token); //解码JWT ，verifier 可复用

            System.out.println(jwt);
        }catch (JWTVerificationException e){
            //无效的签名/声明
            e.printStackTrace();
        }
    }
    public void decodeToken(){
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCIsIm5hbWUiOiJ3dXl1d2VpIiwiZXhwIjoxNTc4NzUyNzEzLCJpYXQiOjE1Nzg3NDU1MTN9.LlC_jiUJI1pe7uEDdmQz4JoL4Qyee3kSY_RWN2ibZmo";
        try {
            DecodedJWT jwt = JWT.decode(token);

            String algorithm = jwt.getAlgorithm(); //获取算法类型
            String type = jwt.getType();	//获取token类型
            String issuer = jwt.getIssuer();	//获取token发布者
            Date expiresAt = jwt.getExpiresAt(); //获取token过期时间
            Date issuedAt = jwt.getIssuedAt();	// 获取token生产日期



            System.out.println(algorithm); 	//=> 	HS256
            System.out.println(type);		//=>	JWT
            System.out.println(issuer);		//=> 	auth0
            System.out.println(expiresAt);	//=>	Sat Jan 11 22:25:13 CST 2020
            System.out.println(issuedAt);	//=>	Sat Jan 11 20:25:13 CST 2020


        } catch (JWTDecodeException e){
            //无效的 token
            e.printStackTrace();
        }
    }

}